package com.shd.edanpei.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shd.edanpei.R;
import com.shd.edanpei.base.BaseActivity;
import com.shd.edanpei.base.BaseNotActionBarActivity;
import com.shd.edanpei.base.data.RxBusCode;
import com.shd.edanpei.base.rxbus.RxBus;
import com.shd.edanpei.base.rxbus.Subscribe;
import com.shd.edanpei.bean.DataBean;
import com.shd.edanpei.bean.TeamModel;
import com.shd.edanpei.citypicker.db.DBManager;
import com.shd.edanpei.common.Constant;
import com.shd.edanpei.db.DaoManager;
import com.shd.edanpei.presenter.contract.MyTeamContract;
import com.shd.edanpei.image.LoadImageCtrl;
import com.shd.edanpei.presenter.MyTeamPresenter;
import com.shd.edanpei.ui.fragment.TeamFragment1;
import com.shd.edanpei.ui.fragment.TeamFragment2;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 团队管理
 */

public class MyTeamActivity extends BaseNotActionBarActivity<MyTeamPresenter> implements MyTeamContract.MyTeamIView {

    public static final int SEARCH = 900;
    public static final int NO_SEARCH = 901;
    private final int picture = 100;

    @BindView(R.id.tv_headline_right)
    TextView tvRight;
    @BindView(R.id.iv_head)
    CircleImageView ivTeamLogo;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_total)
    TextView tvTotal;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.tv_teamName)
    TextView tvTeamName;
    @BindView(R.id.tv_teamCode)
    TextView tvTeamCode;
    @BindView(R.id.tv_teamNumber)
    TextView tvTeamNumber;
    @BindView(R.id.tv_performance)
    TextView tvPerformance;
    @BindView(R.id.tv_rebate)
    TextView tvRebate;
    @BindView(R.id.tv_userName)
    TextView tvUserName;


    private LoadImageCtrl loadImageCtrl;

    private List<String> tabTitle = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private int teamID;
    private int currentTabLayout;
    private boolean isSearchLayout = false;//是否显示未搜索布局
    private String mOrderNumber;//总业绩订单数
    private String mSearchNumber;//搜索业绩订单数


    @Override
    protected int setLayout() {
        return R.layout.activity_myteam;
    }

    @Override
    protected MyTeamPresenter bindPresenter() {
        return new MyTeamPresenter(this);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        RxBus.get().register(this);
        loadImageCtrl = new LoadImageCtrl(this);
        tvUserName.setText("您好："+DaoManager.getInstance().getUserBean().getRealName());
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.queryTeamInfo();

    }

    private void initTabLayoutAndViewPager(int teamID) {
        if (tabTitle.size()>0){
            return;
        }
        tabTitle.add("团队管理");
        tabTitle.add("业绩管理");

        Bundle bundle = new Bundle();
        bundle.putInt(Constant.TEAM_ID, teamID);
        TeamFragment1 teamFragment1 = new TeamFragment1();
        teamFragment1.setArguments(bundle);
        TeamFragment2 teamFragment2 = new TeamFragment2();
        teamFragment2.setArguments(bundle);

        fragments.add(teamFragment1);
        fragments.add(teamFragment2);

//        viewPager.setOffscreenPageLimit(fragments.size());
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {

                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return tabTitle.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return tabTitle.get(position);
            }
        });
        tabLayout.setupWithViewPager(viewPager);
    }


    @Override
    protected void initListener() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {


            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentTabLayout = tab.getPosition();
                initTotalCount(currentTabLayout, mOrderNumber);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        etSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (etSearch.getText().toString().isEmpty()) {
                        return true;
                    } else {
                        RxBus.get().send(SEARCH, etSearch.getText().toString().trim());

                    }
                }
                return false;
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    RxBus.get().send(NO_SEARCH);
                }
            }
        });
    }


    /**
     * 退团审批
     */
    @OnClick(R.id.tv_headline_right)
    void exitCheck() {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.TEAM_ID, teamID);
        startActivity(QuitApprovalActivity.class, bundle);
    }

    @OnClick(R.id.iv_headline_back)
    void onBack() {
        finish();
    }

    @OnClick(R.id.iv_head)
    void onHead() {
        ChoosePicActivity.start(this, picture);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //编辑返回
        if (null != data) {
            switch (resultCode) {
                case picture:
                    String picPath = data.getStringExtra(ChoosePicActivity.INTENT_BACK_DATA);
                    mPresenter.uploadPicture(picPath, teamID);
                    Glide.with(this).load(picPath).into(ivTeamLogo);
                    break;

            }
        }
    }

    /**
     * 设置tabLayout下方订单数量
     *
     * @param count null :隐藏数量栏
     */
    private void initTotalCount(int currentTabLayout, String count) {
        if (currentTabLayout == 0) {
            tvTotal.setVisibility(View.GONE);
        } else {
            if (count.equals("null")) {
                tvTotal.setVisibility(View.GONE);
            } else {
                count = isSearchLayout ? mSearchNumber : mOrderNumber;
                if (count.equals("null")) {
                    tvTotal.setVisibility(View.GONE);
                } else {
                    tvTotal.setVisibility(View.VISIBLE);
                    tvTotal.setText(Html.fromHtml("共完成<font color= '" + getResources().getColor(R.color.main_color) + "'>" + count + "</font>个订单"));
                }
            }
        }
    }


    @Subscribe(code = RxBusCode.SET_ORDER_COUNT)
    public void setTotalCount(String count) {
        isSearchLayout = true;
        mSearchNumber = count;
        initTotalCount(currentTabLayout, count);
    }

    @Subscribe(code = RxBusCode.REMOVE_ORDER_COUNT)
    public void removeTotalCount() {
        isSearchLayout = false;
        mSearchNumber = "null";
        initTotalCount(currentTabLayout, mOrderNumber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unRegister(this);
    }

    @Override
    public void setTeamData(TeamModel data) {
        teamID = data.getTeamId();
        initTabLayoutAndViewPager(teamID);
        tvTeamName.setText(data.getTeamName());
        tvTeamCode.setText(data.getTeamCode());
        tvTeamNumber.setText(data.getTeamNum());
        tvPerformance.setText(new StringBuilder().append("¥").append(data.getTotalPerformance()));
        tvRebate.setText(new StringBuilder().append("返利：¥").append(data.getRebateAmount()));
        mOrderNumber = data.getOrdersNum();
        initTotalCount(currentTabLayout, mOrderNumber);
        if (!TextUtils.isEmpty(data.getTeamPic())) {
            loadImageCtrl.getGlide().load(data.getTeamPic()).into(ivTeamLogo);
        }
    }
}
